package manager

import (
	"fmt"
	"github.com/duke-git/lancet/v2/slice"
)

var (
	ActionInfoManager = NewActionManager()
)

type ActionInfo struct {
	Name     string
	Type     string
	Discript string
}

func (i ActionInfo) GetBrief() string {
	return fmt.Sprintf("%v  (%v)", i.Name, i.Discript)
}

type ActionManager struct {
	data map[string]*ActionInfo
}

func NewActionManager() *ActionManager {
	return &ActionManager{
		data: map[string]*ActionInfo{},
	}
}

func (m *ActionManager) RegisterActionInfo(info *ActionInfo) {
	if m.data[info.Name] != nil {
		panic(fmt.Sprintf("action %v is already registered", info.Name))
	}
	m.data[info.Name] = info
}

func (m *ActionManager) IsActionSupport(action string) bool {
	return m.data[action] != nil
}

func (m *ActionManager) GetActionInfo(name string) *ActionInfo {
	return m.data[name]
}

func (m *ActionManager) ActionBriefs() []string {
	var brief []string
	actions := make([]*ActionInfo, 0, len(m.data))
	for _, action := range m.data {
		actions = append(actions, action)
	}
	slice.SortBy(actions, func(a, b *ActionInfo) bool {
		return a.Name < b.Name
	})
	for _, info := range actions {
		brief = append(brief, info.GetBrief())
	}
	return brief
}

func (m *ActionManager) GetActionNameByBrief(brief string) string {
	for _, info := range m.data {
		if info.GetBrief() == brief {
			return info.Name
		}
	}
	return ""
}
